import Vue from 'vue'
import VueRouter from 'vue-router'

import login from '../components/login.vue'
import hello from '../components/hello.vue'
import home from '../components/home.vue'
import welcome from '../components/welcome.vue'
// import { from } from 'core-js/fn/array'
import users from '../components/user/users.vue'

Vue.use(VueRouter)


const router = new VueRouter({
  routes : [
    {
      path:'/hello',
      name:'hello',
      component:hello
    },
    
    {
      path:'/login',
      name:'login',
      component:login
    },
    {
      path:'/home',
      name:'home',
      component:home,
      redirect:'/welcome',
      children:[
        {path:'/welcome',component:welcome},
       {path:'/users',component:users}]
    },
    {
      path:'/',
      redirect:'/login'
    }
  ]
})


// 添加路由守卫
router.beforeEach((to,from,next)=>{
  //如果用户访问登录页，直接放行
  if(to.path==='/login') return next();
  //从session.storage获取token
  const tokenStr = window.sessionStorage.getItem('token');
  //没有token，返回登录页
  if(!tokenStr) return next('/login');
  next();

})

export default router
